//
//  WebViewController.m
//  PaiLeXiongProject
//
//  Created by 小獾科技 on 2017/8/21.
//  Copyright © 2017年 小獾科技. All rights reserved.
//

#import "WebViewController.h"
#import <WebKit/WebKit.h>
#import "Jockey.h"
#import "SubmitOrderViewController.h"
#import "ApplyViewController.h"
#import "DiaryCommentViewController.h"
#define kJockeyListenKey                @"pailexiong"     //监听key
#define kJockeyBackKey                  @"back"           //返回
#define kJockeyCollectKey               @"collect"        //收藏
#define kJockeyShareKey                 @"share"          //分享
#define kJockeyBuyKey                   @"buy"            //立即购买
#define kJockeyTelPhone                 @"phone"          //打电话


@interface WebViewController ()<WKNavigationDelegate, WKUIDelegate, UIScrollViewDelegate, WKScriptMessageHandler>

@property (nonatomic, strong) WKWebView *wkWebView;
@property (nonatomic, strong) UIButton *collectionBtn;
@property (nonatomic, strong) UIButton *shareBtn;

@property (nonatomic, strong) NSDictionary *param;

@property (nonatomic, copy) NSString *imgUrl;
@property (nonatomic, copy) NSString *link;
@property (nonatomic, copy) NSString *shareTitle;

@property (nonatomic, strong) ShareModel *shareModel;// 分享model

@end

@implementation WebViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.hidesBottomBarWhenPushed = YES;
    self.title = @"";
    [self addBackItem];
    [self createWebView];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_urlStr]];
    [request addValue:[GW_Tool getHttpHeaderCookieString] forHTTPHeaderField:@"Cookie"];
    [_wkWebView loadRequest:request];
    
    
    NSLog(@"webUrl = %@", _urlStr);
    if([self.titleName isEqualToString:@"首页"])
    {
        [NetWork sendGetRequestURL:[NSString stringWithFormat:@"%@/collect/isCollect?type=%@&cid=%@", GW_Domain, @"1", self.goodid] parameters:@{@"type":@"1", @"cid":self.goodid} completionBlockWithSuccess:^(NSDictionary *resultDict) {
            NSLog(@"收藏 %@", resultDict);
            if([[NSString stringWithFormat:@"%@", resultDict[@"data"][@"iscollect"] ] isEqualToString:@"1"])
            {
                _collectionBtn.selected = YES;
            }
            else
                _collectionBtn.selected = NO;
        } andFailure:^(NSError *error, NSString *errorMsg) {
            NSLog(@"%@", error);
        }];
    
    }
    _collectionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_collectionBtn setImage:IMAGE(@"collect_default") forState:0];
    [_collectionBtn setImage:IMAGE(@"collect") forState:UIControlStateSelected];
    _collectionBtn.hidden = YES;
    [_collectionBtn addTarget:self action:@selector(handleCollectionAction:) forControlEvents:UIControlEventTouchUpInside];
    [_collectionBtn setTitleColor:ColorRed forState:0];
    _collectionBtn.frame = CGRectMake(0, 0, 20, 20);
    UIBarButtonItem *collct = [[UIBarButtonItem alloc] initWithCustomView:_collectionBtn];
    
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
    UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithCustomView:label];
    
    
    _shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_shareBtn setImage:IMAGE(@"share") forState:0];
    _shareBtn.hidden = YES;
    [_shareBtn addTarget:self action:@selector(handleShareAction) forControlEvents:UIControlEventTouchUpInside];
    _shareBtn.frame = CGRectMake(0, 0, 20, 20);
    UIBarButtonItem *share = [[UIBarButtonItem alloc] initWithCustomView:_shareBtn];
    if([self.titleName isEqualToString:@"首页"])
    {
        self.navigationItem.rightBarButtonItems = @[collct, btn, share];
    }
    else if([self.titleName isEqualToString:@"体验"])
    {
        self.navigationItem.rightBarButtonItems = @[share];
    }
    
    
    self.link = self.urlStr;
}


- (void)backItemAction
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"homeChange" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

//收藏
- (void)handleCollectionAction:(UIButton *)sender
{
    if(!IS_LOGIN)//先判断是否登录  没有登录则去登录
    {
        MESSAGE_TOAST(@"未登录，请先登录");
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotiShowLoginVC object:nil];
        return;
    }
    
    if(sender.selected == YES)
    {
        MESSAGE_TOAST(@"您已收藏，请勿重复收藏");
        return;
    }
    
    
    NSDictionary *param;
    if([self.titleName isEqualToString:@"首页"])
    {
        param = @{@"type":@"1",
                  @"cid" :self.goodid};
    }
    [NetWork sendPostRequestURL:[NSString stringWithFormat:@"%@/collect/SetCollect", GW_Domain] parameters:param completionBlockWithSuccess:^(NSDictionary *resultDict) {
        sender.selected = YES;
        MESSAGE_TOAST(resultDict[@"message"]);
    } andFailure:^(NSError *error, NSString *errorMsg) {
        NSLog(@"%@", error);
    }];
}

//分享
- (void)handleShareAction
{
    ShareModel *model = [ShareModel new];
    //测试微信分享
    model.title = self.title;
    model.imgUrl = self.imgUrl;
    model.link = self.link;
    model.desc = self.desc;
    [[ShareView sharedInstance] showShareViewWithModel:model andCallback:^{
        MESSAGE_TOAST(@"分享成功");
    }];
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    if([message.name isEqualToString:@"buy"])
    {
        NSLog(@"购买");
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [[UINavigationBar appearance] setTranslucent:NO];
    self.navigationController.navigationBar.barTintColor = ColorWhite;
    
    // Listen for a JS event.
    // action 是和web定义的一个关键词
    [Jockey on:@"pailexiong" performAsync:^(WKWebView *webView, NSDictionary *payload, void (^complete)()) {
    
        NSLog(@"payload = %@",payload);
        
        [self handleJockeyDict:payload];
    }];
    
    if([_titleName isEqualToString:@"首页"])
    {
        _collectionBtn.hidden = NO;
        _shareBtn.hidden = NO;
    }
    else if([_titleName isEqualToString:@"体验"])
    {
        _shareBtn.hidden = NO;
    }
    
}

- (void)handleJockeyDict:(NSDictionary *)payload
{
    if([payload[@"key"] isEqualToString:@"buy"])
    {
        if(!IS_LOGIN)
        {
            MESSAGE_TOAST(@"请先登录");
            [[NSNotificationCenter defaultCenter] postNotificationName:kNotiShowLoginVC object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"homeChange" object:nil];

            return;
        }
        
        NSDictionary *dict = payload[@"data"];
        SubmitOrderViewController *payVC = [SubmitOrderViewController new];//提交订单界面
        payVC.hidesBottomBarWhenPushed = YES;
        payVC.goodsName = dict[@"goodName"];
        payVC.sale_price = dict[@"sale_price"];
        payVC.goodId = dict[@"gid"];
        
        [self.navigationController pushViewController:payVC animated:YES];
    }
    else if ([payload[@"key"] isEqualToString:@"phone"])
    {
        [GW_Tool telephoneCallup:payload[@"data"]];//打电话
    }
    else if ([payload[@"key"] isEqualToString:@"apply"])
    {
        if(!IS_LOGIN)
        {
            MESSAGE_TOAST(@"请先登录");
            [[NSNotificationCenter defaultCenter] postNotificationName:kNotiShowLoginVC object:nil];
            return;
        }
        ApplyViewController *applyVC = [ApplyViewController new];//申请界面
        applyVC.strId = payload[@"data"];
        applyVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:applyVC animated:YES];
    }
    else if ([payload[@"key"] isEqualToString:@"pinglun"])
    {
        if(!IS_LOGIN)
        {
            MESSAGE_TOAST(@"请先登录");
            [[NSNotificationCenter defaultCenter] postNotificationName:kNotiShowLoginVC object:nil];
            return;
        }
        DiaryCommentViewController *VC = [DiaryCommentViewController new];//日记评论界面
        VC.goodid = self.goodid;
        @weakobj(self);
        VC.refresgBlock = ^{
            @strongobj(self);
            [self.wkWebView reload];
        };
        [self.navigationController pushViewController:VC animated:YES];
    }
    else if ([payload[@"key"] isEqualToString:@"share"]) // 分享
    {
        NSDictionary *dic = payload[@"data"];
        [self handleShareModelWithDict:dic];
        [self showShareView];
//        self.param = dic;
//        self.link = dic[@"link"];
//        self.titleName = dic[@"title"];
//        self.imgUrl = dic[@"imgUrl"];//图片大小不得超过32k不然分享不出去
//        [self handleShareAction];
     }
    else if ([payload[@"key"] isEqualToString:@"login"])
    {
        [self loginMethod];
    }
}

//登录调用的方法
- (void)loginMethod {
    
    if (TOKEN.length > 0) {
        
        // 已经登录，直接发送token
        NSDictionary *sendDict = @{@"token":TOKEN};
        [Jockey send:@"login" withPayload:sendDict toWebView:self.wkWebView perform:nil];
        
    } else {
        
        @weakobj(self);
        CompleteVoidBlock loginSuccessBlock = ^(void) {
            
            @strongobj(self);
            
            // 发送方法
            NSDictionary *sendDict = @{@"token":TOKEN};
            [Jockey send:@"login" withPayload:sendDict toWebView:self.wkWebView perform:nil];
        };
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotiShowLoginVC object:loginSuccessBlock];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"homeChange" object:nil];

    }
}

//------------------分享------------------------------
- (void)handleShareModelWithDict:(NSDictionary *)dict {
    
    if (!_shareModel) {
        _shareModel = [ShareModel new];
    }
    _shareModel.title   = STRING(dict[@"title"]);
    _shareModel.desc    = STRING(dict[@"desc"]);
    _shareModel.imgUrl  = STRING(dict[@"imgUrl"]);
    _shareModel.link    = STRING(dict[@"link"]);
    _shareModel.key     = STRING(dict[@"key"]);
}

- (void)showShareView {
    
    if ([WXApi isWXAppInstalled]) {
        
        [self.view endEditing:YES];
        // 弹出 shareView
        @weakobj(self);
        [[ShareView sharedInstance] showShareViewWithModel:self.shareModel andCallback:^(void) {
            NSLog(@"分享成功");
            @strongobj(self);
            [Jockey send:kJockeyShareKey withPayload:@{@"success":@"1"} toWebView:self.wkWebView perform:nil];
            
        }];
    } else {
        MESSAGE_TOAST(@"未检测到相关客户端");
    }
}



-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    return [Jockey webView:_wkWebView withUrl:[request URL]];
}

- (void)createWebView
{
//    WKUserContentController *userContentController = [[WKUserContentController alloc] init];
////    [userContentController addScriptMessageHandler:self name:@"buy"];
//    
//    // WKWebView的配置
//    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
//    configuration.userContentController = userContentController;
    
//    // 读取 UserAgent
//    UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds ];
//    NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
////    NSString *newUserAgent = [userAgent stringByAppendingString:@" answernApp answernIOS"];
//    
//    
//    if ([[[UIDevice currentDevice] systemVersion] doubleValue] < 9) {
//        // iOS8 重写 UserAgent（放在初始化之前）
////        NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
//        NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:userAgent, @"UserAgent", nil];
//
//        [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
//    }
    
    _wkWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, GWIDTH, GHEIGHT - 64) configuration:[self configWKCookie]];
    _wkWebView.allowsBackForwardNavigationGestures = YES;//是否允许左右划手势导航，默认不允许
    _wkWebView.UIDelegate = self;
    _wkWebView.navigationDelegate = self;
    _wkWebView.scrollView.delegate = self;
    if(iOS9)
    {
        _wkWebView.allowsLinkPreview = NO;
    }
    [self.view addSubview:_wkWebView];
    _wkWebView.translatesAutoresizingMaskIntoConstraints = NO;
    
    
//    if (iOS9) {
//        // iOS9 重写 UserAgent（放在初始化之后， loadRequest 之前）
////        self.wkWebView.customUserAgent = newUserAgent;
//        self.wkWebView.customUserAgent = userAgent;
//    }
}

//配置WK Cookie
- (WKWebViewConfiguration *)configWKCookie
{
    WKUserContentController* userContentController = [WKUserContentController new];
    
    WKUserScript * cookieScript = [[WKUserScript alloc]initWithSource:[GW_Tool getWebConfigCookieScript]
                                                        injectionTime:WKUserScriptInjectionTimeAtDocumentStart
                                                     forMainFrameOnly:NO];
    [userContentController addUserScript:cookieScript];
    WKWebViewConfiguration* webViewConfig = [WKWebViewConfiguration new];
    webViewConfig.userContentController = userContentController;
    
    return webViewConfig;
}


#pragma mark - WKNavigationDelegate

// 页面开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {

    //    NSLog(@"%s", __FUNCTION__);
}

// 内容开始返回
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    
    //    NSLog(@"%s", __FUNCTION__);
}

// 页面加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
    //    NSLog(@"%s", __FUNCTION__);
    
//    [self configRightItems];// 返回页面时重新设置右上角按钮
    
    // title
    [webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
        self.title = STRING(obj);
    }];
    
    // UMeng Hybrid
    [webView evaluateJavaScript:@"setWebViewFlag()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        
    }];
    
    // 禁止选择
    [webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';" completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
        
    }];
    // 禁止长按
    [webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
        
    }];
}

// 加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
    NSLog(@"%s", __FUNCTION__);
    NSLog(@"%@", [error description]);
}

// 接收到服务器跳转请求之后
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
    
    //    NSLog(@"%s", __FUNCTION__);
}


- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
    
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        
        if ([challenge previousFailureCount] == 0) {
            
            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            
            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
            
        } else {
            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        }
        
    } else {
        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
    }
}

// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
     if (![Jockey webView:webView withUrl:navigationAction.request.URL]) {
        
        // Jockey
        decisionHandler(WKNavigationActionPolicyCancel);
        
     }
    else {
        
        // Default
        decisionHandler(WKNavigationActionPolicyAllow);
    }
    
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        completionHandler();
    }]];
    [self presentViewController:alertController animated:YES completion:^{}];
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        completionHandler(YES);
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        completionHandler(NO);
    }]];
    [self presentViewController:alertController animated:YES completion:^{}];
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:prompt preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = defaultText;
        //        textField.text = defaultText;
    }];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSString *input = ((UITextField *)alertController.textFields.firstObject).text;
        completionHandler(input);
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        completionHandler(nil);
    }]];
    [self presentViewController:alertController animated:YES completion:^{}];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [Jockey off:@"pailexiong"];
}

- (void)dealloc
{
    _wkWebView.scrollView.delegate = nil;
    _wkWebView.navigationDelegate = nil;
    _wkWebView.UIDelegate = nil;
}

- (void)viewDidAppear:(BOOL)animated
{
    [[UINavigationBar appearance] setTranslucent:NO];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
    self.navigationController.navigationBar.barTintColor = ColorWhite;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
